package com.dulichdanang.location.locationCat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lib.map.MyMedia;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.util.Log;


public class LocationCat {
	public int id;
	public int imageResource;
	public String name;
	public String subTitle;
	public Drawable image;
	public List<LocationCat> getLocationCat(){
		List<LocationCat> locationCats = new ArrayList<LocationCat>();
		JSONArray jArray;
		String result = null;
		InputStream is = null;
		StringBuilder sb = null;
		//Phần này tạo kết nối
				try{
				     HttpClient httpclient = new DefaultHttpClient();
				     HttpPost httppost = new HttpPost("http://10.0.2.2:8080/webservice/index.php/locationcat/getall");
				     HttpResponse response = httpclient.execute(httppost);
				     HttpEntity entity = response.getEntity();
				     is = entity.getContent();
				     }catch(Exception e){
				         Log.e("log_tag", "Error in http connection"+e.toString());
				    }
				
				// Đọc dữ liệu về dưới dạng chuỗi
				try{
				      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
				       sb = new StringBuilder();
				       sb.append(reader.readLine() + "\n");

				       String line="0";
				       while ((line = reader.readLine()) != null) {
				                      sb.append(line + "\n");
				        }
				        is.close();
				        result=sb.toString();
				        }catch(Exception e){
				              Log.e("log_tag", "Error converting result "+e.toString());
				   }
				//paring data 
				try{
				      jArray = new JSONArray(result);
				      JSONObject json_data=null;
				      for(int i=0;i<jArray.length();i++){
				             json_data = jArray.getJSONObject(i);
				             LocationCat locationcat = new LocationCat();
				             locationcat.id = json_data.getInt("id");
				             locationcat.name = json_data.getString("name");
				             locationcat.image = MyMedia.LoadImageFromWebOperations(json_data.getString("image"),"image");
				             locationcat.subTitle = json_data.getString("des");
				             locationCats.add(locationcat);
				         }
				      return locationCats;
				      }
				      catch(JSONException e1){
				    	  e1.printStackTrace();
				      } catch (ParseException e1) {
				    	 e1.printStackTrace();
				      }
		return null;
		
	}
}
